package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    private static final int PAGE_SIZE = 3;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int page, Model model) {
        List<Student> students = studentRepository.findAll(page, PAGE_SIZE);
        long totalCount = studentRepository.count();
        int totalPages = (int) Math.ceil((double) totalCount / PAGE_SIZE);

        model.addAttribute("students", students);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "student/list";
    }

    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("student", new Student());
        return "student/form";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute Student student, @RequestParam String birthdayStr) {
        try {
            Date birthday = DATE_FORMAT.parse(birthdayStr);
            student.setBirthday(birthday);
            studentRepository.save(student);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "redirect:/student/list";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable String id, Model model) {
        Student student = studentRepository.findById(id);
        model.addAttribute("student", student);
        return "student/form";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        studentRepository.delete(id);
        return "redirect:/student/list";
    }
}    